package com.shark.commons.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shark.commons.mybatis.BaseMapper;
import com.shark.commons.spring.SpringContextHolder;
import com.shark.commons.web.model.AjaxResponse;
import com.shark.commons.web.model.DataGrid;
import com.shark.commons.web.model.SystemContext;

public abstract class BaseService<T> implements IService<T> {
	
	@Autowired
	private BaseMapper<T> baseMapper ;

	@Override
	public int insert(T entity) {
		return this.baseMapper.insert(entity);
	}

	@Override
	public int insertSelective(T entity) {
		return this.baseMapper.insertSelective(entity);
	}

	@Override
	public int deleteByPrimaryKey(Object id) {
		return this.baseMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(T entity) {
		return this.baseMapper.updateByPrimaryKeySelective(entity);
	}

	@Override
	public int updateByPrimaryKey(T entity) {
		return this.baseMapper.updateByPrimaryKey(entity);
	}

	@Override
	public T selectByPrimaryKey(Object id) {
		return this.baseMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<T> selectAll() {
		return this.baseMapper.selectAll();
	}

	@Override
	public AjaxResponse add(T entity) {
		AjaxResponse ajaxResponse = SpringContextHolder.getBean(AjaxResponse.class).reset() ;
		if(insertSelective(entity) > 0) {
			ajaxResponse.setStatus(true);
			ajaxResponse.setMessage("保存成功！");
		} else {
			ajaxResponse.setStatus(false);
			ajaxResponse.setMessage("保存失败！");
		}
		return ajaxResponse;
	}

	@Override
	public AjaxResponse update(T entity) {
		AjaxResponse ajaxResponse = SpringContextHolder.getBean(AjaxResponse.class).reset() ;
		if(updateByPrimaryKeySelective(entity) > 0) {
			ajaxResponse.setStatus(true);
			ajaxResponse.setMessage("修改成功！");
		} else {
			ajaxResponse.setStatus(false);
			ajaxResponse.setMessage("修改失败！");
		}
		return ajaxResponse;
	}

	@Override
	public AjaxResponse deleteBatchByKeys(Long[] ids) {
		AjaxResponse ajaxResponse = SpringContextHolder.getBean(AjaxResponse.class).reset() ;
		int deleteBatchByKeys = this.baseMapper.deleteBatchByKeys(ids); 
		if(deleteBatchByKeys > 0) {
			ajaxResponse.setStatus(true);
			ajaxResponse.setMessage("批量删除成功！");
		} else {
			ajaxResponse.setStatus(false);
			ajaxResponse.setMessage("批量删除失败！");
		}
		return ajaxResponse;
	}

	@Override
	public List<T> selectByPage(T entity) {
		PageHelper.startPage(SystemContext.getPageNum(), SystemContext.getPageSize()) ;
		return this.baseMapper.selectByPage(entity);
	}

	@Override
	public DataGrid<T> datagrid(T entity) {
		DataGrid<T> dg = new DataGrid<T>();
		
		PageHelper.startPage(dg.getPageNum(), dg.getPageSize());
		List<T> list = selectByPage(entity) ;
		PageInfo<T> pInfo = new PageInfo<T>(list) ;
		
		dg.setRows(list);
		dg.setTotal(pInfo.getTotal());
        
		return dg;
	}

	
}
